#include "core/GameState.h"
#include "core/GameConteiner.h"
#include "component/Doodle.h"
#include "component/Animation.h"
#include "util/FPS.h"

using namespace eats_core;

GameState::GameState(){
	_working_surface = GameConteiner::getInstance()->getGameManager()->_core_surface;
	if(_working_surface == NULL){
		std::cout << "|ERROR| A superficie nucle está nula.  " << std::endl;
	}
	goldMeter = 0;
}

bool GameState::render()
{
	if( !_working_surface )
	{
		return false;
	}

	SDL_FillRect(_working_surface, &background.screenRect, background.clearColor);

    for( unsigned int i = 0; i < objList.size() ; i ++) {
        ( objList.at(i) )-> render();
    }
    SDL_Flip(_working_surface);

    return true;
}


void GameState::update(){
    for( unsigned int i = 0; i < objList.size() ; i ++) {
        ( objList.at(i) )-> update();
    }

}


void GameState::event(SDL_Event* Event)
{
    onEvent(Event);
}

bool GameState::setUp()
{
	std::cout << "|INFO| Iniciando a configuração do estado: "<< _canonical_name << std::endl;

	background.screenRect.x = background.screenRect.y = 0;
	background.screenRect.w = _working_surface->w;
	background.screenRect.h = _working_surface->h;
	background.clearColor = SDL_MapRGB(_working_surface->format, 255, 255, 255);

	bool ret = true;
	std::cout << "|INFO| Iniciando carregamento de objetos (número de objetos: " << objList.size() << ") " <<std::endl;
    for( unsigned int i = 0; i < objList.size() ; i ++) {
    	std::cout << "|INFO| Iniciando carregamento do objeto: "<< objList.at(i)->_canonical_name << std::endl;
    	if ( ( objList.at(i) )-> setUp() != true ) {
        	std::cout << "|WARNING| Não foi possível carregar o objeto ["<< objList.at(i)->_canonical_name<<"]" << std::endl;
			ret = false;
		} else {
			std::cout << "|INFO| Carregamento efetuado com sucesso, objeto ["<< objList.at(i)->_canonical_name<<"]" << std::endl;
		}
    }
    std::cout << "|INFO| Carregamento de objetos finalizado, resultado final (1 = Sucesso, 0 = Falha) : "<< ret <<std::endl;


    return ret;
}

void GameState::tearDown()
{
    for( unsigned int i = 0; i < objList.size() ; i ++) {
        ( objList.at(i) )->tearDown();
        delete objList.at(i);
    }
}

//Eventos Suportados::

void GameState::exitEvent()
{
    GameConteiner::getInstance()->getGameManager()->turnOFF();
    state = idle;
}

bool GameState::disableObject ( GameObject * ref )
{
	vector<GameObject *>::iterator iter = objList.begin();
	for( int i = 0;	iter != objList.end(); iter++, i++) {
		if( objList.at(i) == ref ){
			objList.erase(iter);
			return true;
		}
	}
	return false;
}

